"""
Configuration management for GSI Wiki Generator
"""

import json
import os
from pathlib import Path
from typing import Dict, Any, Optional
from dataclasses import dataclass


@dataclass
class WikiConfig:
    """Configuration class for GSI Wiki Generator"""
    
    # Input/Output paths
    input_directory: str = "/home/docker/comgsi/tutorial/comGSIv3.7_EnKFv1.3/src/comGSI-wiki"
    output_directory: str = "./gsi_wiki_output"
    outline_file: str = "gsi_drp4dvar_wiki_outline.json"
    
    # Codebase-RAG settings
    max_results: int = 10
    min_score: float = 0.2
    
    # Processing settings
    claude_timeout: int = 120
    search_timeout: int = 60
    
    # Cache settings
    enable_cache: bool = True
    cache_directory: str = "cache"
    
    @classmethod
    def from_file(cls, config_file: str) -> 'WikiConfig':
        """Load configuration from JSON file"""
        if not os.path.exists(config_file):
            # Create default config if it doesn't exist
            config = cls()
            config.save_to_file(config_file)
            return config
            
        with open(config_file, 'r', encoding='utf-8') as f:
            data = json.load(f)
        
        return cls(**data)
    
    def save_to_file(self, config_file: str) -> None:
        """Save configuration to JSON file"""
        os.makedirs(os.path.dirname(config_file), exist_ok=True)
        
        with open(config_file, 'w', encoding='utf-8') as f:
            json.dump(self.__dict__, f, indent=2, ensure_ascii=False)
    
    def get_absolute_input_path(self) -> Path:
        """Get absolute path for input directory"""
        return Path(self.input_directory).resolve()
    
    def get_absolute_output_path(self) -> Path:
        """Get absolute path for output directory"""
        return Path(self.output_directory).resolve()
    
    def get_outline_path(self) -> Path:
        """Get path to outline file in input directory"""
        return self.get_absolute_input_path() / self.outline_file
    
    def validate(self) -> bool:
        """Validate configuration settings"""
        input_path = self.get_absolute_input_path()
        outline_path = self.get_outline_path()
        
        if not input_path.exists():
            raise ValueError(f"Input directory does not exist: {input_path}")
        
        if not outline_path.exists():
            raise ValueError(f"Outline file does not exist: {outline_path}")
        
        if self.max_results <= 0:
            raise ValueError("max_results must be positive")
        
        if not 0 <= self.min_score <= 1:
            raise ValueError("min_score must be between 0 and 1")
        
        return True


def load_default_config() -> WikiConfig:
    """Load default configuration"""
    config_file = Path(__file__).parent.parent.parent / "config" / "default.json"
    return WikiConfig.from_file(str(config_file))


def create_config_template(output_file: str) -> None:
    """Create a configuration template file"""
    config = WikiConfig()
    config.save_to_file(output_file)
    print(f"Configuration template created: {output_file}")